package com.gzz.orchid.common.webmvc.support.limiter.manager;

import com.gzz.orchid.common.core.exception.BizzException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;

import java.util.Collections;
import java.util.Objects;

/**
 * @author higmd
 */
@Slf4j
public class RedisLimitManager implements ILimiterManager {
    private final StringRedisTemplate stringRedisTemplate;

    public RedisLimitManager(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean tryAccess(Limiter limiter) {
        log.info("Access -- 执行Redis limiter key={}", limiter.getKey());
        String key = limiter.getKey();
        if (Objects.isNull(key) || key.isEmpty()) {
            throw new BizzException("Redis limiter key cannot be null");
        }

        int seconds = limiter.getSeconds();
        int limitCount = limiter.getLimitNum();
        // lua脚本
        String luaScript = buildLuaScript();
        RedisScript<Long> redisScript = new DefaultRedisScript<>(luaScript, Long.class);
        Long count = stringRedisTemplate.execute(redisScript, Collections.singletonList(key), limitCount, seconds);
        log.info("Access try count is {} for key={}", count, key);

        return count != 0;
    }

    /**
     * 构建lua脚本
     */
    private String buildLuaScript() {
        return "";
    }
}